import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class FpsTextComponent extends StatefulWidget {
  const FpsTextComponent({super.key});

  @override
  State<StatefulWidget> createState() => _FpsTextComponentState();
}

const REFRESH_RATE = 90;
const _frameInterval =
    Duration(microseconds: Duration.microsecondsPerSecond ~/ REFRESH_RATE);

class _FpsTextComponentState extends State<FpsTextComponent> {
  int _fps = 0;

  @override
  void initState() {
    super.initState();
    WidgetsFlutterBinding.ensureInitialized().addTimingsCallback((timings) {
      var framesCount = timings.length;
      var costCount = timings.map((t) {
        // 耗时超过 frameInterval 会导致丢帧
        //ui或者是raster时间超过单个周期，才认为是丢帧，参考devTool的标准
        if (t.buildDuration.inMicroseconds >= _frameInterval.inMicroseconds ||
            t.rasterDuration.inMicroseconds >= _frameInterval.inMicroseconds) {
          return t.buildDuration.inMicroseconds ~/ _frameInterval.inMicroseconds +
              t.rasterDuration.inMicroseconds ~/ _frameInterval.inMicroseconds +
              1;
        } else {
          return 1;
        }
      }).fold(0, (a, b) => a + b);
      double fps = framesCount * REFRESH_RATE / costCount;
      setState(() {
        //静态下，单次回调是一帧信息，但是这个绘制时间比较长，还不了解具体机制，但是这里应该用最大帧率体现绘制效率
        if (timings.length == 1) {
          _fps = REFRESH_RATE;
        } else {
          _fps = fps.round();
        }
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text("FPS:$_fps",style: const TextStyle(color: Color(0xffFFEBEE),fontSize: 16),);
  }
}
